//
//  TradeViewController.m
//  bitcoin
//
//  Created by  旺链 on 2018/5/24.
//  Copyright © 2018年 比特币. All rights reserved.
//

#import "TradeViewController.h"
#import "MarketViewController.h"
#import "TradeMainView.h"
#import "MyOrderViewController.h"
#import "TradeListTableViewCell.h"
#import "CCHStepSizeSlider.h"
#import "TradeSectionHeaderView.h"
#import "CurrentDeputeTableViewCell.h"
#import "BillboardListViewController.h"

@interface TradeViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString *payCurrency;
    NSString *tradeCurrency;
    
    //NSArray *temArr;
    //买入卖出状态
    NSInteger businessType;
    
    //法币名称
    NSString *bName;
}
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)UIButton *favBtn;

@property (nonatomic,strong)NSMutableArray *buyAndSellArr;

@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)TradeMainView *headView;
@property(nonatomic,strong)UIView *footView;
@property(nonatomic,strong)UIView *maskView;
@property(nonatomic,strong)MarketViewController *market;
@property(nonatomic,strong)UITableView *table;
//@property(nonatomic,strong)TradeSectionHeaderView *sectionHeader;
@property(nonatomic,assign)BOOL isTest;

@end

@implementation TradeViewController
@synthesize isBuy = _isBuy;

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getBname];
    if (IsLogin) {
        [self.headView.loginOrBuyBtn setTitle:[NSString stringWithFormat:@"买入%@",tradeCurrency] forState:UIControlStateNormal];
        self.headView.allOrderBtn.hidden = NO;
        
//        self.dataArr.array = temArr;
//        [self.table reloadData];
        
        
    }else{
        [self.headView.loginOrBuyBtn setTitle:@"登录" forState:UIControlStateNormal];
        self.headView.allOrderBtn.hidden = YES;
        
//        self.dataArr.array = @[];
//        [self.table reloadData];
    }
   
    [self.timer setFireDate:[NSDate distantPast]];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.timer setFireDate:[NSDate distantFuture]];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"展开-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(spreadClick:)];
    self.navigationItem.leftBarButtonItem = back;
    
    //addactive-icon
    self.favBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [self.favBtn setImage:[UIImage imageNamed:@"add-icon"] forState:UIControlStateNormal];
    [self.favBtn setImage:[UIImage imageNamed:@"addactive-icon"] forState:UIControlStateSelected];
    [self.favBtn addTarget:self action:@selector(requestForFav:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *add = [[UIBarButtonItem alloc]initWithCustomView:self.favBtn];
    
//    UIBarButtonItem *add = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"add-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(requestForFav:)];
    UIBarButtonItem *chart = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"chart-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(chartShow)];
    
    self.navigationItem.rightBarButtonItems = @[chart,add];
    
    [self.view addSubview:self.table];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeUI:) name:@"changeUI" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeFav:) name:@"refreshMyFav" object:nil];
    
//    self.relation = @"BTC/ETH";
//    self.relationId = @"2";
//    self.currencyId = @"2";
    businessType = 1;
//    [self getBname];
//    [self getDefaultRelation];
}
- (void)getDefaultRelation:(NSString *)relationId
{
    NSString *url = [NSString stringWithFormat:@"defaultRelationId/%@",relationId];
    [LSRequestManager getRequestWithURL:MARKET(url) params:nil success:^(NSDictionary *responseData) {
        
        HandleResponse(
                       NSDictionary *dic = responseData[@"data"];
                       self.relation = dic[@"currencyRelation"];
                       self.relationId = dic[@"currencyRelationId"];
                       self.currencyId = dic[@"currencyId"];
                       self.headView.precisionDic = dic;
                       
                       if (IsLogin) {
                       self.favBtn.selected = [dic[@"flagFav"] integerValue]==0?NO:YES;
                       }
                       //刷新数据
                       [self getData];
                       )}
        
    } failure:^(NSError *error) {
        
    }];
}
- (void)getBname
{
    if ([[UserDefaults objectForKey:K_PRICE]isEqualToString:@"1"]) {
        bName = @"CNY";
    }else if ([[UserDefaults objectForKey:K_PRICE]isEqualToString:@"2"]){
        bName = @"USD";
    }else{
        bName = @"AUD";
    }
}
- (void)getCurrency:(NSString *)relation
{//切割交易币 支付币
    NSArray *arr = [relation componentsSeparatedByString:@"/"];
    tradeCurrency = arr[0];
    payCurrency = arr[1];
}
- (void)setCurrencyId:(NSString *)currencyId
{
    _currencyId = currencyId;
    self.headView.bId = currencyId;
}
#pragma mark 获取实时数据
- (void)getData
{
    if (!self.relationId) {
        
        return;
    }
    //获取买卖价格 实时成交价
    [self getBuyAndSellOrder];
    
    if (IsLogin) {
        
        //获取可用资产
        [self getUsableAssets];
        //获得当前委托
        [self getCurrentOrder];
    }
}

- (void)getBuyAndSellOrder
{
    //获取买卖价格 实时成交价
    NSString *sellurl = [NSString stringWithFormat:@"listSellOrder/%@",self.relationId];
    
    [LSRequestManager getRequestWithURL:MARKET(sellurl) params:nil success:^(NSDictionary *responseData) {
        
        if (!responseData) {
            return ;
        }
        
        HandleResponse(
                       [self.buyAndSellArr removeAllObjects];
                       NSArray *arr = responseData[@"data"];
                       NSMutableArray *temarr = [NSMutableArray array];
                       for (NSInteger i=arr.count-1; i>arr.count-1-5; i--) {
                           [temarr addObject:arr[i]];
                       }
                       temarr.array = [[temarr reverseObjectEnumerator]allObjects];
                       [self.buyAndSellArr addObject:temarr];
                       
                       //获取买单
                       [self getBuyOrder];
        )}
    } failure:^(NSError *error) {
        
    }];
    
}
- (void)getBuyOrder
{//获取买单
    NSString *buyurl = [NSString stringWithFormat:@"listBuyOrder/%@",self.relationId];
    [LSRequestManager getRequestWithURL:MARKET(buyurl) params:nil success:^(NSDictionary *responseData) {
        if (!responseData) {
            return ;
        }
        HandleResponse(
                       NSArray *arr2 = responseData[@"data"];
                       NSMutableArray *temarr2 = [NSMutableArray array];
                       for (NSInteger i=0; i<5; i++) {
                           [temarr2 addObject:arr2[i]];
                       }
                       [self.buyAndSellArr addObject:temarr2];
        
        NSLog(@"1--------%lu",(unsigned long)self.buyAndSellArr.count);
        if (self.buyAndSellArr.count != 2) {
            return ;
        }
                       //获取最新价
                       [self getNewestPrice];
                       
                       ) }
     } failure:^(NSError *error) {
         
     }];
}
- (void)getNewestPrice
{//获取最新价
    NSString *NewTransactionPriceurl = @"newPriceCurrencyConversion";
    NSDictionary *dic = @{@"relationId":self.relationId,@"bcurrencyId":self.currencyId,@"mark":bName};
    
    [LSRequestManager postRequestWithURL:MARKET(NewTransactionPriceurl) params:dic success:^(NSDictionary *responseData) {
        
        if (self.buyAndSellArr.count !=2) {
            return ;
        }
        HandleResponse(
                       NSLog(@"2--------%lu",(unsigned long)self.buyAndSellArr.count);
                       
                       [self.buyAndSellArr addObject:responseData[@"data"]];
                       
                       
                       )[self.buyAndSellArr addObject:@(0)];}
     NSLog(@"3------------%lu",(unsigned long)self.buyAndSellArr.count);
     
     self.headView.listArr = self.buyAndSellArr;
     } failure:^(NSError *error) {
         
     }];
}
- (void)getCurrentOrder
{//获得当前委托
    
    NSDictionary *para = @{@"pageSize":@(20),@"pageNum":@(1),@"businessType":@(businessType),@"currencyPay":payCurrency,@"currencyTrade":tradeCurrency};
    [LSRequestManager postRequestWithURL:MARKET(@"listPersonalOrderCurrent") params:para success:^(NSDictionary *responseData) {
        
                if ([responseData[@"data"] isKindOfClass:[NSNull class]]) {
                    self.table.tableFooterView = self.footView;
                    return ;
                }
                HandleResponse(
        
                               [self.dataArr removeAllObjects];
                               [self.dataArr addObjectsFromArray:responseData[@"data"][@"listOrderVO"]];
                               if(self.dataArr.count == 0){
                                   self.table.tableFooterView = self.footView;
                               }else{
                                   self.table.tableFooterView = nil;
                               }
                               
                               [self.table reloadData];
                        )}
    
     } failure:^(NSError *error) {
         
     }];
//    NSString *orderurl = @"listMallOrderCurrent";
//    NSDictionary *para = @{@"pageSize":@"20",@"pageNum":@"1",@"businessType":@(businessType),@"relationId":self.relationId};
//
//    [LSRequestManager postRequestWithURL:MARKET(orderurl) params:para success:^(NSDictionary *responseData) {
//
//        if ([responseData[@"data"] isKindOfClass:[NSNull class]]) {
//            self.table.tableFooterView = self.footView;
//            return ;
//        }
//        HandleResponse(
//
//                       [self.dataArr removeAllObjects];
//                       [self.dataArr addObjectsFromArray:responseData[@"data"]];
//                       if(self.dataArr.count == 0){
//                           self.table.tableFooterView = self.footView;
//                       }else{
//                           self.table.tableFooterView = nil;
//                       }
//                       self.dataArr = responseData[@"data"];
//                       [self.table reloadData];
//                       )}
//
//
//    } failure:^(NSError *error) {
//
//    }];
}
- (void)getUsableAssets
{//获取可用资产
    NSDictionary *para = @{@"currencyPay":payCurrency,@"currencyTrade":tradeCurrency,@"legalCurrency":bName};
    [LSRequestManager postRequestWithURL:MARKET(@"myFund/") params:para success:^(NSDictionary *responseData) {
        
        
        
        HandleResponse(
                       self.headView.assetsData = responseData[@"data"];
        
                       )
        self.headView.assetsData = nil;
    }
    } failure:^(NSError *error) {
        
    }];
}
- (void)addOrder:(NSDictionary *)para
{//下单
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:para];
    [dic setValue:self.relationId forKey:@"relationId"];
    
    [LSRequestManager postRequestWithURL:MARKET(@"addOrder") params:dic success:^(NSDictionary *responseData) {
        
        HandleResponse(
                       [self performSelector:@selector(getCurrentOrder) withObject:nil afterDelay:1];
                       [self performSelector:@selector(getUsableAssets) withObject:nil afterDelay:1];
                       //[self getCurrentOrder];
                       )}
    } failure:^(NSError *error) {
        
    }];
}
- (void)spreadClick:(UIButton*)btn
{//左页面弹出
    UIView *leftVi = self.maskView;
    leftVi.frame =CGRectMake(-ScreenWidth, 0, ScreenWidth, ScreenHeight);
    
    [self.view.window addSubview:leftVi];
    
    [UIView animateWithDuration:0.3 animations:^{
       
        leftVi.frame =CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    }];
}
- (void)requestForFav:(UIButton *)btn
{
    if (!IsLogin) {
        [MBProgressHUD showSuccess:@"请先登录"];
        return;
    }
    //加入自选
    [LSRequestManager postRequestWithURL:MARKET(@"addFav/") params:@{@"relationId":self.relationId} success:^(NSDictionary *responseData) {
        
        HandleResponse(
                       
                       btn.selected = !btn.selected;
                       )}
    } failure:^(NSError *error) {
        
    } showHUD:YES];
}
- (void)chartShow
{//k线图
    
}
- (void)changeFav:(NSNotification*)noti
{//行情自选变化
    NSString *relationId = noti.object;
    if (relationId.integerValue ==  self.relationId.integerValue) {
        
        self.favBtn.selected = !self.favBtn.selected;
    }
}
//点击买入卖出，变化
- (void)changeUI:(NSNotification* )noti
{
    if ([noti.object isEqualToString:@"0"]) {
        
        businessType = 1;
        //self.sectionHeader.typeLb.textColor = [UIColor colorWithHexString:@"#2CB25A"];
        
    }else{
        
        businessType = 2;
        //self.sectionHeader.typeLb.textColor = [UIColor colorWithHexString:@"#E1454F"];
    }
    if (IsLogin) {
         [self getCurrentOrder];
    }
}
- (NSTimer *)timer
{
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(netWorking) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSDefaultRunLoopMode];
    }
    return _timer;
}
- (void)netWorking
{//网络请求
    if (self.relationId) {
        [self getDefaultRelation:self.relationId];
        
    }else{
        [self getDefaultRelation:@"0"];
    }

}
- (void)setRelationId:(NSString *)relationId
{
    _relationId = relationId;
}
- (void)setRelation:(NSString *)relation
{
    _relation = relation;
    self.navigationItem.title = relation;
    [self getCurrency:self.relation];
    
    //设置单位
    self.headView.currencyRelation = relation;
//    self.headView.tradeCurrency = tradeCurrency;
//    self.headView.payCurrency = payCurrency;
}
- (NSMutableArray *)dataArr
{//订单数组
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
- (NSMutableArray *)buyAndSellArr
{//买  卖 实时价格
    if (!_buyAndSellArr) {
        _buyAndSellArr = [NSMutableArray array];
    }
    return _buyAndSellArr;
}
- (MarketViewController *)market
{//左弹框
    if (!_market) {
        _market = [[MarketViewController alloc]init];
        _market.menuViewStyle = WMMenuViewStyleLine;
        _market.isLeft = YES;
        _market.view.frame =CGRectMake(0, 0, ScreenWidth-rightSpace, ScreenHeight);
        
        [_market.searchBtn setImage:[UIImage imageNamed:@"展开-icon-1"] forState:UIControlStateNormal];
        [_market.searchBtn addTarget:self action:@selector(tapClick) forControlEvents:UIControlEventTouchUpInside];
        
        __weak TradeViewController *weak = self;
        _market.clickBack = ^(NSDictionary*dic) {
            
            NSString *relation = dic[@"currencyRelation"];
            NSString *relationId = dic[@"currencyRelationId"];
            NSString *flagFav = dic[@"flagFav"];
            
            weak.currencyId = dic[@"currencyId"];
            weak.relation = relation;
            weak.relationId = relationId;
            //刷新数据
            [weak getData];
            [weak tapClick];
            
            weak.favBtn.selected = [flagFav integerValue]==0?NO:YES;
            
            //精度
            weak.headView.precisionDic = dic;
        };
    }
    
    return _market;
}
- (BOOL)isBuy
{//获得 买入卖出状态
    
    //    self.headView.selectBtn == self.headView.buyInBtn
    //    买入
    if (self.headView.selectBtn == self.headView.buyInBtn) {
        return YES;
    }else{
        return NO;
    }
    
}

- (void)setIsBuy:(BOOL)isBuy
{//修改 买入卖出状态
    
    UIButton *seletBtn;
    if (isBuy) {
        seletBtn =self.headView.buyInBtn;
        
        businessType = 1;
    }else{
        seletBtn =self.headView.soldOutBtn;
        
        businessType = 2;
    }
    
    if (seletBtn == self.headView.buyInBtn) {
        //买入
        [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUI" object:@"0"];
        
    }else{
        //卖出
        [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUI" object:@"1"];

    }
    
}
- (UIView *)maskView
{//左弹框背景图
    if (!_maskView) {
        
        _maskView  = [[UIView alloc]initWithFrame:CGRectMake(-ScreenWidth, 0, ScreenWidth, ScreenHeight)];
        _maskView.backgroundColor = [UIColor colorWithRed:0/255 green:0/255 blue:0/255 alpha:0.5];
        [_maskView addSubview:self.market.view];
        
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-rightSpace, 0, rightSpace, ScreenHeight)];
        [_maskView addSubview:btn];
        [btn addTarget:self action:@selector(tapClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _maskView;
}
- (void)tapClick
{//左弹框 消失
    [UIView animateWithDuration:0.3 animations:^{
        
        self.maskView.frame = CGRectMake(-ScreenWidth, 0, ScreenWidth, ScreenHeight);
    } completion:^(BOOL finished) {
        [self.maskView removeFromSuperview];
    }];
    
}
//- (TradeSectionHeaderView *)sectionHeader
//{
//    if (!_sectionHeader) {
//
//        _sectionHeader = [[[NSBundle mainBundle]loadNibNamed:@"TradeSectionHeaderView" owner:self options:nil]firstObject];
//        _sectionHeader.killOrder = ^{
//          //撤单
//
//        };
//    }
//    return _sectionHeader;
//}
- (TradeMainView *)headView
{
    if (!_headView) {
        _headView = [[[NSBundle mainBundle]loadNibNamed:@"TradeMainView" owner:self options:nil]firstObject];
        
        __weak TradeViewController *weakSelf = self;
        _headView.loginOrBuy = ^(NSDictionary *para){
            if (IsLogin) {
                //下单
                [weakSelf addOrder:para];
            }else{
                //弹出登录页面
                BaseNavigationController *base = [[UIStoryboard storyboardWithName:@"Login" bundle:nil] instantiateInitialViewController];
                [weakSelf presentViewController:base animated:NO completion:nil];
            }
        };
        _headView.allOrder = ^{
            MyOrderViewController *order = [[MyOrderViewController alloc]init];
            order.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:order animated:YES];
            
        };
    }
    return _headView;
}
- (UITableView *)table
{
    if (!_table) {
        
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-(NavgationHeight)-(TabBarHeight))];
        _table.backgroundColor = [UIColor colorWithHexString:@"#1C2035"];
        
        _table.delegate = self;
        _table.dataSource = self;
        
        
//        TradeMainView *v =
//        //v.frame = CGRectMake(0, 0, ScreenWidth, 420);
//        [self.view addSubview:v];
//
//        [v mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.left.right.equalTo(0);
//            make.height.equalTo(420);
//        }];
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
        _table.tableHeaderView = self.headView;
        
        [_table registerNib:[UINib nibWithNibName:@"CurrentDeputeTableViewCell" bundle:nil] forCellReuseIdentifier:@"CurrentDeputeTableViewCell"];
    }
    return _table;
}
- (UIView *)footView
{
    if (!_footView) {
        
        _footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
        UILabel *la = [[UILabel alloc]initWithFrame:_footView.frame];
        la.textColor = [UIColor whiteColor];
        la.text = @"暂无数据";
        la.textAlignment = NSTextAlignmentCenter;
        [_footView addSubview:la];
    }
    return _footView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CurrentDeputeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CurrentDeputeTableViewCell"];
    NSDictionary *dic = self.dataArr[indexPath.row];
    [cell configWidthData:dic];
    //撤单
    cell.unDoBack = ^{
        
        [self unDoPost:dic[@"id"]];
    };
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (void)unDoPost:(NSString*)orderid
{
    [LSRequestManager postRequestWithURL:MARKET(@"undoOrder") params:@{@"orderId":orderid} success:^(NSDictionary *responseData) {
        
        HandleResponse(
                       
                       [MBProgressHUD showError:responseData[@"msg"]];
                       
                       //刷新列表
                       [self getCurrentOrder];
                       )}
    } failure:^(NSError *error) {
        
    } showHUD:YES];
}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    return self.sectionHeader;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 60;
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
